package com.androturka;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.androturka.IDataAdapter.EarthQuake;
import com.androturka.IDataAdapter.IArrayListDataListener;
import com.google.android.c2dm.C2DMessaging;

//import de.vogella.android.c2dm.R;

public class Main extends Activity {
	
	private static final String ACTION_MAIN = "android.intent.action.MAIN";
	private static final String LATITUDE = "latitude";
	private static final String LONGITUDE = "longitude";
	private static final String ACTION_SHOW_LOCATION_ONMAP = "com.listview.showLocationMap";
	private static final String ACTION_SHOW_ALL_ONMAP = "com.listview.showAllMap";
	private static final String LOCATION = "com.listview.location";
	private static final String DATE = "com.listview.date";
	private static final String MAGNITUDE = "com.listview.magnitude";
	private static final Integer DEFAUL_EARTHQUAKE_COUNT = 100;
	private EarthQuake[] earthquakes;
	
	//private static final String TAG = "Deprem";
	private ProgressDialog pDialog;
	int eqCount = DEFAUL_EARTHQUAKE_COUNT;
	String search_keyword;
	private ListView listView;

	private LocationManager locationManager;
	private String bestProvider;
	public Location location;
	
	private EarthQuakeAdapter earthQuakeAdapter;
	private int eartquakeCount;
	
	int notificationID = 1;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		//Toast.makeText(this, "Starting", Toast.LENGTH_LONG).show();

		C2DMessaging.register(this, "depremgunlugu@gmail.com");
		//super.onCreate(savedInstanceState);

		//final EarthQuakeNotification eqNotification = new EarthQuakeNotification( getApplicationContext());
		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

		Criteria criteria = new Criteria();
		bestProvider = locationManager.getBestProvider(criteria, false);		
		
		location = locationManager.getLastKnownLocation(bestProvider);		
		if ( location != null )
			Toast.makeText(Main.this, "Konum Bilgisi Başarıyla Alındı",Toast.LENGTH_SHORT).show();
		else
			Toast.makeText(Main.this, "Konum Bilgisi Alınamadı",Toast.LENGTH_SHORT).show();
		
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		listView = (ListView) findViewById(R.id.listView1);

		String action = getIntent().getAction();
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		
		AlertDialog.Builder ad = new AlertDialog.Builder(this);
		ad.setMessage(R.string.Internet_uyari);
		ad.setPositiveButton(R.string.tamam,
			new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
					finish();
				}
		});
		if (netInfo != null && netInfo.isConnectedOrConnecting()) {

			pDialog = ProgressDialog.show(Main.this, "",getString(R.string.datayukleniyor), true, true);
			IDataAdapter adapter = new WebAdapter();

			if ( action.equals(ACTION_MAIN) )
			{
				adapter.getEarthQuakeList("getEarthQuakes","count",Integer.toString(eqCount), new IArrayListDataListener() {
				//adapter.getEarthQuakeList("getAfterEarthQuakes","afterdate","20120420", new IArrayListDataListener() {
					@Override
					public void dataArrived(ArrayList<Object> data) {
						if (data != null) {
							eartquakeCount = data.size();
							Toast.makeText(Main.this, eartquakeCount + " Tane Deprem Bilgisi Başarıyla Alındı",Toast.LENGTH_LONG).show();
							
							if (eartquakeCount > 0) {
								earthquakes = new EarthQuake[eartquakeCount];
								for (int i = 0; i < eartquakeCount; i++) {
									earthquakes[i] = (EarthQuake) data.get(i);
									if ( location != null )
										earthquakes[i].distance = distFrom(location.getLatitude(),location.getLongitude(),earthquakes[i].latitude,earthquakes[i].longitude);
									else
										earthquakes[i].distance = (double) -1;
									
									//eqNotification.checkFilters(earthquakes[i]);
								}
								earthQuakeAdapter = new EarthQuakeAdapter(
										getApplicationContext(), earthquakes );

								listView.setAdapter(earthQuakeAdapter);
							}
						}
						pDialog.cancel();
					}
				});
			}

			listView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {

					Toast.makeText(Main.this, "Harita hazırlanıyor",
							Toast.LENGTH_SHORT).show();
														
					EarthQuake earthquake = (EarthQuake) (listView.getAdapter()
							.getItem(position));

					SimpleDateFormat df = new SimpleDateFormat("dd MMMM HH:mm");
					String formattedDate = df.format(earthquake.date);
					
					Intent i = new Intent(Main.this, Harita.class);
					i.putExtra(LATITUDE, earthquake.latitude);
					i.putExtra(LONGITUDE, earthquake.longitude);
					i.putExtra(LOCATION, earthquake.location);
					i.putExtra(DATE, formattedDate);
					i.putExtra(MAGNITUDE, earthquake.magnitude);
					i.setAction(ACTION_SHOW_LOCATION_ONMAP);
					startActivity(i);
				}
			});
		} else
			ad.show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();

		inflater.inflate(R.menu.mainmenu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		final Dialog dialog = new Dialog(this);
		
		switch (item.getItemId()) {
			case R.id.hakkinda:				
				dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
				dialog.setContentView(R.layout.about);
				dialog.show();
	
				Button positiveButton = (Button) dialog
						.findViewById(R.id.positiveButton);
	
				positiveButton.setOnClickListener(new OnClickListener() {
	
					@Override
					public void onClick(View arg0) {
						dialog.cancel();
					}
				});
				break;
			case R.id.refresh:
				Intent refreshIntent = new Intent(Main.this, Main.class);
				refreshIntent.setAction(ACTION_MAIN);
				startActivity(refreshIntent); 
				break;
			
			case R.id.settings:
				Intent settingsIntent = new Intent(getApplicationContext(), Settings.class);
				startActivity(settingsIntent);
				break;
				
			case R.id.filters:
				
				Intent filtersIntent = new Intent(getApplicationContext(), FiltersActivity.class);
				startActivity(filtersIntent);
				
				//startService(new Intent(this, ClientService.class));

				break;
				
			case R.id.siralaBuyuklugeGore:
				
				if ( earthquakes != null ){
					Arrays.sort(earthquakes, new Comparator<EarthQuake>(){
					    @Override
						public int compare(EarthQuake element1, EarthQuake element2){
					 	   
					    	Double element1Magnitude = element1.magnitude;
					        Double element2Magnitude = element2.magnitude;
					       
					        //-1 ile çarpmazsak kucukten buyuge siraliyor.
					        return -1*element1Magnitude.compareTo(element2Magnitude);
					    }
					});
					listView.setAdapter(earthQuakeAdapter);
					Toast.makeText(Main.this, "Depremler Büyüklüğüne Göre Sıralandı",Toast.LENGTH_LONG).show();
				}
				break;
	
			case R.id.siralaTariheGore:
				if ( earthquakes != null ){
					Arrays.sort(earthquakes, new Comparator<EarthQuake>(){
					    @Override
						public int compare(EarthQuake element1, EarthQuake element2){
		
					        Date element1Date = element1.date;
					        Date element2Date = element2.date;
		
					        //-1 ile çarpmazsak kucukten buyuge siraliyor.
					        return -1*element1Date.compareTo(element2Date);
					    }
					});
					
					listView.setAdapter(earthQuakeAdapter);
					Toast.makeText(Main.this, "Depremler Tarihe Göre Sıralandı",Toast.LENGTH_LONG).show();
				}	
				break;
	
			case R.id.siralaYakinligaGore:
				if ((location != null) || ( earthquakes != null )) {
					Arrays.sort(earthquakes, new Comparator<EarthQuake>(){
					    @Override
						public int compare(EarthQuake element1, EarthQuake element2){
		
					        Double element1Distance = element1.distance;
					        Double element2Distance = element2.distance;
		
					        return element1Distance.compareTo(element2Distance);
					    }
					});
					
					listView.setAdapter(earthQuakeAdapter);
					Toast.makeText(Main.this, "Depremler Yakınlığına Göre Sıralandı",Toast.LENGTH_LONG).show();
	
				}
				else {
					Toast.makeText(getApplicationContext(), "Konum Bilgisi Alınamıyor", Toast.LENGTH_LONG).show();
				}
				
				break;
			case R.id.tumunuharitadagoster:
				Toast.makeText(Main.this, "Harita hazırlanıyor",
						Toast.LENGTH_SHORT).show();
				
				String[] latitudes = new String[eartquakeCount];
				String[] longitudes = new String[eartquakeCount];
				String[] locations = new String[eartquakeCount];
				String[] formatteddates = new String[eartquakeCount]; 
				String[] magnitudes = new String[eartquakeCount];
				
				for (int ii = 0; ii < eartquakeCount; ii++) {
					latitudes[ii]=Double.toString(earthquakes[ii].latitude);
					longitudes[ii]=Double.toString(earthquakes[ii].longitude);
					locations[ii]=earthquakes[ii].location;
					magnitudes[ii]=Double.toString(earthquakes[ii].magnitude);
					SimpleDateFormat df = new SimpleDateFormat("dd MMMM HH:mm");
					formatteddates[ii] = df.format(earthquakes[ii].date);
				}
				
				Intent i = new Intent(Main.this, Harita.class);
				i.putExtra(LOCATION, locations);
				i.putExtra(DATE, formatteddates);
				i.putExtra(LATITUDE, latitudes);
				i.putExtra(LONGITUDE, longitudes);
				i.putExtra(MAGNITUDE, magnitudes);
				i.setAction(ACTION_SHOW_ALL_ONMAP);
				startActivity(i);
	
				break;
			
		} //switch


		return super.onOptionsItemSelected(item);
	}
	
	public static double distFrom(double lat1, double lng1, double lat2, double lng2) {
		double earthRadius = 3958.75;
		double dLat = Math.toRadians(lat2-lat1);
		double dLng = Math.toRadians(lng2-lng1);
		double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
		           Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
		           Math.sin(dLng/2) * Math.sin(dLng/2);
		double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
		double dist = earthRadius * c;
		
		return dist;
    }
}